<template>
    <div class="warpper-box">
      <div class="inner_box">
       <form-create 
       v-model="params.fApi" 
       :rule="params.rule" 
       :option="params.option" 
       @btn-search-click="loadList(true)" 
       @btn-add-click="verifyClick('','form','申请采购计划')" 
       @btn-del-batch-click="delBatchPurchase" 
       @btn-reset-click="reset"/>
       <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane v-for="(item,index) in tab" :key="index" :label="item.label" :name="item.value">
          <label slot="label">
            <span style="cursor: pointer;">{{item.label}}</span>
            <template v-for="(value, key) in interfaceTab">
              <template v-if="value.stateId === parseInt(item.value)">
                <font class="badge" :key="key" v-if="value.num!==0">{{value.num}}</font>
              </template>
            </template>
          </label>
          <purchase-list
          :key="keys"
          :tableData="tables.tableData" 
          :tableLabel="tables.tableLabel" 
          :models="tables" 
          @on-search-click="loadList"
          @on-verify-click="function(row){return verifyClick(row,'initVerify','内勤审核')}"
          @on-carryVerify-click="function(row){return verifyClick(row,'initVerify','分管领导审核')}"
          @on-sendVerify-click="function(row){return verifyClick(row,'initVerify','总经理审核')}"
          @on-stop-click="stopPurchase"
          @on-details-click="function(row){return verifyClick(row,'detailsVerify','物资采购计划详情')}"
          @on-againVerify-click="function(row){return verifyClick(row,'formReject','重构物资采购计划')}"
          @on-againOtherVerify-click="function(row){return verifyClick(row,'initVerifyReject','重构物资采购计划')}"
          @on-selection-click="selectionChange"
          @on-del-click="del"/>
        </el-tab-pane>
      </el-tabs>
     
        <el-dialog :title="verify.title" :visible.sync="verify.form.visible" :width="verify.width" :close-on-click-modal="false">
          <purchaseApply v-if="verify.form.hackReset" :row="verify.row" @on-cancel-click="onCancel"/>
        </el-dialog>
        <el-dialog :title="verify.title" :show-close="false" :visible.sync="verify.formReject.visible" :width="verify.width" :close-on-click-modal="false">
          <purchaseApplyReject v-if="verify.formReject.hackReset" :row="verify.row" @on-cancel-click="onCancel"/>
        </el-dialog>
        <el-dialog :title="verify.title" :show-close="false" :visible.sync="verify.initVerify.visible" :width="verify.width" :close-on-click-modal="false">
          <purchaseInitVerify v-if="verify.initVerify.hackReset" :row="verify.row" @on-cancel-click="onCancel"/>
        </el-dialog>
        <el-dialog :title="verify.title" :show-close="false" :visible.sync="verify.initVerifyReject.visible" :width="verify.width" :close-on-click-modal="false">
          <purchaseInitVerifyReject v-if="verify.initVerifyReject.hackReset" :row="verify.row" @on-cancel-click="onCancel"/>
        </el-dialog>
        <el-dialog :title="verify.title" :visible.sync="verify.detailsVerify.visible" :width="verify.width" :close-on-click-modal="false">
          <purchaseDetails v-if="verify.detailsVerify.hackReset" :row="verify.row" @on-cancel-click="onCancel"/>
        </el-dialog> 
        
      </div>
    </div>
  </template>
  
  <script>
  import store from '@/store'
  import { arrayFormat } from "@/utils/index"
  import { 
    PARAMS_PURCHASE_PLAN,
    LABEL_PURCHASE_PLAN,
    LABEL_PURCHASE_OTHER_PLAN,
    PURCHASE_TAB,
    OPTION_INLINE
  } from "@/views/purchase/purchaseModel/purchase_form"
  import PurchaseList from "@/views/purchase/purchaseModel/purchase_model_list"
  import purchaseApply from "@/views/purchase/purchaseNode/purchase_apply"
  import purchaseApplyReject from "@/views/purchase/purchaseNode/purchase_apply_reject"
  import purchaseInitVerify from "@/views/purchase/purchaseNode/purchase_init_verify"
  import purchaseInitVerifyReject from "@/views/purchase/purchaseNode/purchase_init_verify_reject"
  import purchaseDetails from "@/views/purchase/purchaseNode/purchase_details"
  import { 
    purchaseStateTount,
    purchaseList,
    purchaseSave,
    purchaseEdit,
    purchaseDelBatch,
    purchaseReject,
    purchaseDel
  } from "@/api/purchase_api"
  export default {
    components:{
        PurchaseList,
        purchaseApply,
        purchaseApplyReject,
        purchaseInitVerify,
        purchaseInitVerifyReject,
        purchaseDetails
    },
    data() {
      return {
        keys:0,
        activeName:"2",
        tab:PURCHASE_TAB,
        interfaceTab:[],
        params:{
          fApi:{},
          rule:PARAMS_PURCHASE_PLAN,
          option:OPTION_INLINE
        },
        tables:{
          total:0,
          fixed:'right',
          width:'300px',
          hackReset:true,
          tableData:[],
          tableLabel: LABEL_PURCHASE_PLAN
        },
        page:{
          jobStateId:"2",
          pageNum:1,
          pageSize:10,
        },
        verify:{
          row:'',
          title:'采购计划审核',
          width:"1400px",
          form:{
            visible:false,
            hackReset:true
          },
          formReject:{
            visible:false,
            hackReset:true
          },
          initVerify:{
            visible:false,
            hackReset:true
          },
          initVerifyReject:{
            visible:false,
            hackReset:true
          },
          detailsVerify:{
            visible:false,
            hackReset:true
          }
        },
        selectItem:[]
      };
    },
    mounted() {

      //处理从工作台跳转过来
      this.activeName = this.$route.params.activeName === undefined ? '2': this.$route.params.activeName;
      this.page.jobStateId = this.$route.params.activeName === undefined ? '2': this.$route.params.activeName;

      this.loadList(true);
      this.$nextTick(()=>{
        this.params.fApi.setValue({"projectId":"","time":""});
      });
      this.getCount();
      this.getProjectSelect();
    },
    methods: {
      //每个状态统计
      async getCount(){
        const {msg,code,data} = await purchaseStateTount();
        this.interfaceTab = data;
      },
      //获取项目库列表
      async getProjectSelect(){
        const _project = await store.dispatch('user/getProjectSelect');
        const _roleList = arrayFormat(_project);
        this.params.fApi.updateRule('projectId', {
            options: _roleList
        }, true)
      },
      //列表
      async loadList(formData) {
        let params = this.params.fApi.bind();
        if(params.time && params.time.length != 0){
          params.startTime = params.time[0];
          params.endTime = params.time[1];
        }
        if(formData !== undefined && formData.type === 'page'){
          this.page.pageNum = formData.pageNum;
          this.page.pageSize = formData.pageSize;
        }
        if(formData===true){
          this.page.pageNum = 1;
          this.keys++;
        }
        params.jobStateId = this.page.jobStateId;
        params.pageNum = this.page.pageNum;
        params.pageSize = this.page.pageSize;
        this.getCount();//获取最新统计
        const req = await purchaseList(params);
        if(req.code === 200){
          this.tables.tableData = req.data.list;
          let btn = this.$store.getters.permission_btns;
          if(btn.includes('purchaseAddCode')){
            this.params.fApi.hidden(false,'add')
          }else{
            this.params.fApi.hidden(true,'add')
          }
          if(btn.includes('purchaseDelBatchCode')){
            this.params.fApi.hidden(false,'delBatch')
          }else{
            this.params.fApi.hidden(true,'delBatch')
          }
          /* 
            jobStateId==1 已驳回
            jobStateId==2 内勤审核
            jobStateId==3 分管领导审核
            jobStateId==4 总经理审核
            jobStateId==5 已成功
            jobStateId==6 已终止
          */
         let user = this.$store.getters.permission_user;
          this.tables.tableData.forEach(v=>{

            if(btn.includes("purchaseAgainVerifyCode")){//重新审核按钮

              //驳回状态
              if(v.jobStateId === 1){
                let handleUser = v.handleUser && v.handleUser !=='' ? v.handleUser.split(',') : [];
                if(handleUser.includes(String(user.id))){//判断驳回的人员是否是当前登录人员
                  v.againVerify = true;//重新审核
                }
              }

            }
            if(btn.includes("purchaseStopCode")){
              if(v.jobStateId === 1 || v.jobStateId === 2){//内勤未审核，驳回的采购可以终止
                v.stop = true;//终止
              }
            }
            if(btn.includes("purchaseDelCode")){
              if(v.jobStateId === 6 || v.jobStateId === 2){//内勤未审核，驳回的采购可以删除
                v.del = true;
              }
            }
            if(btn.includes("purchaseVerifCode")){ //内勤审核按钮
              //当前状态是内勤审核 并且checkFlag==='0' 才显示内勤审核按钮
              if(v.jobStateId === 2 && v.checkFlag === '0'){
                v.verify = true;//内勤
              }
              //当前状态内勤审核 如果是驳回 1 就显示重新审核 0是正常
              if(v.jobStateId ===2 && v.checkFlag === '1'){
                  v.againOtherVerify = true;//重新审核
              }
            }
           
            if(btn.includes("purchaseCarryVerifyCode")){
               //当前状态是分管领导审核 并且checkFlag==='0' 才显示内勤审核按钮
              if(v.jobStateId === 3 && v.checkFlag === '0'){
                v.carryVerify = true;//分管领导
              }
              //当前状态分管领导审核 如果是驳回 1 就显示重新审核 0是正常
              if(v.jobStateId ===3 && v.checkFlag === '1'){
                  v.againOtherVerify = true;//重新审核
              }
            }
            if(btn.includes("purchaseSendVerifyCode")){
              if(v.jobStateId === 4){
                v.sendVerify = true;//总经理
              }
            }
            if(btn.includes("purchaseDelCode")){
              if(v.jobStateId === 5){//已经完成的采购计划 放出删除按钮  修改日期2022-07-21
                v.del = true;
              }
            }
            v.details = true;
          })
          this.tables.total = req.data.total;
        }
      },
      //切换
      handleClick(obj){
        this.page.jobStateId = obj.name;
        //处理驳回列表和其他列表 因为驳回理由特殊处理
        if(obj.name === '1'){
          this.tables.tableLabel = LABEL_PURCHASE_OTHER_PLAN;
        }else{
          this.tables.tableLabel = LABEL_PURCHASE_PLAN;
        }
        this.loadList(true);
      },
      //单个删除
      del(row){
        this.$confirm("确认删除", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          let req = await purchaseDel(row.id);
          if(req.code === 200){
            this.$message.success("删除成功");
            this.loadList();
          }
        }).catch(() => {});
      },
      //获取选中id
      selectionChange(arr){
        this.selectItem = arr;
      },
      //批量删除
      delBatchPurchase(){
        if(this.selectItem.length === 0){
          return this.$message.error("请选择删除的数据");
        }
        this.$confirm("确认批量删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
        }).then(async () => {
          let ids = [];
          this.selectItem.forEach(v=>{
            ids.push(v.id)
          })
          let {code,msg} = await purchaseDelBatch(ids);
          if(code === 200){
              this.$message.success("删除成功");
              this.loadList();
          }
        }).catch(() => {});
      },
      //终止采购
      stopPurchase(row){
        this.$confirm("终止后无法恢复，是否终止", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
            /*
            fromStateId	当前步骤ID
            handleUser	处理人ID	
            planId	采购计划ID		
            stepName	当前步骤名称
            suggestion	办理意见	
            toStateId	变更到状态ID	
            */
           
            const params = {
                fromStateId:row.jobStateId,
                handleUser:row.handleUser,
                planId:row.id,
                suggestion:row.rejectReason,
                stepName:'驳回',
                toStateId:6,
            }
            const {code,msg} = await purchaseReject(params);
            if(code === 200){
              this.$message.success("操作成功");
              this.loadList();
            }
        }).catch(() => {});
      },
      //新增和每个节点审核弹出框
      verifyClick(row,typeVisible,title){
        this.verify.row = row;
        this.verify.title = title;
        this.verify[typeVisible].hackReset = false;
        this.$nextTick(()=>{
          this.verify[typeVisible].hackReset = true;
        })
        this.verify[typeVisible].visible = true;
      },
      reset(){
        this.params.fApi.resetFields();
        this.loadList(true);
      },
      onCancel(flag){
        this.verify[flag].visible = false;
        this.loadList(true);
      }
    }
  };
  </script>